package main

import (
	"errors"
	"flag"
	"fmt"
	"github.com/hpcloud/tail"
	"google.golang.org/grpc"
	"net"
	"tailf/proto"
)

var username, password, addr string

func init() {
	flag.StringVar(&username, "username", "logtail", "username")
	flag.StringVar(&password, "password", "logtail", "password")
	flag.StringVar(&addr, "listenAddr", "0.0.0.0:9090", "listen addr")
	flag.Parse()
}

type LogTail struct {
	username string
	password string
}

func (l *LogTail) Tail(req *proto.LogRequest, stream proto.LogTail_TailServer) error {
	if req.GetUsername() != l.username || req.GetPassword() != l.password {
		return errors.New("username or password is not right")
	}
	t, err := tail.TailFile(req.GetFilename(), tail.Config{
		ReOpen:    true,
		Follow:    true,
		MustExist: true,
	})
	if err != nil {
		return err
	}
	defer t.Stop()
	for line := range t.Lines {
		if line.Err != nil {
			return line.Err
		}
		err = stream.Send(&proto.LogResponse{Line: line.Text})
		if err != nil {
			return err
		}
	}
	return nil
}

func main() {
	grpcServer := grpc.NewServer()
	proto.RegisterLogTailServer(grpcServer, &LogTail{username: username, password: password})

	l, err := net.Listen("tcp4", addr)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	defer l.Close()

	fmt.Println("logtail server listen at:", addr)

	err = grpcServer.Serve(l)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
}
